import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/tokenOperate'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          await store.dispatch('user/getUserInfo')
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          if (accessRoutes && accessRoutes.length > 0) {
            accessRoutes.forEach(item => {
              router.addRoute(item)
            })
          }
          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message({
            message: error,
            type: 'error'
          })
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next({ path: '/login' })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
